#!/usr/bin/env sh

# Copyright (c) 2018 noamcore. All rights reserved.

source /usr/local/bin/colors

trap 'printf "\n===> Aborting...\n"; exit 1' SIGINT

EDITOR=${EDITOR:-vim}
TERMINAL=xst

readonly name=$0
readonly version=1.0-beta

declare -A config_files=(
	[polybar]=~/.config/polybar/config
	[bspwm]=~/.config/bspwm/bspwmrc
	[me]=$name
)

function usage()
{
	printf "%s $version\n" "${name}"
	echo
	echo "usage: %s [options]" "${name}"
	echo
	echo "    -h, --help     this help"
	echo
	echo "These options can be passed:"
	echo "    theme          change GTK theme"
}

die() {
	printf "${red}==> ERROR: $1${reset}\n" "${@:2}" >&2
	exit 1
}

function cursor()
{
	PS3='Selecione o tema do cursor: '
	select cursor_name in $(ls /usr/share/icons); do
	case "$cursor_name" in
		*)
			sed -i "s/\(Inherits=\).*/\1$cursor_name/" ~/.icons/default/index.theme
			if [ -f ~/.config/gtk-3.0/settings.ini ]; then
				sed -i "s/\(gtk-cursor-theme-name=\).*/\1$cursor_name/" ~/.config/gtk-3.0/settings.ini
			fi
			if [ -f ~/.config/.gtkrc-2.0 ]; then
				sed -i "s/\(gtk-cursor-theme-name=\).*/\1$cursor_name/" ~/.config/.gtkrc-2.0
			fi
			xsetroot -cursor_name left_ptr
			break
			;;
	esac
	done
}

function theme()
{
	PS3='Selecione o tema: '
	select theme_name in $(ls /usr/share/themes); do
	case "$theme_name" in
		*)
			sed -i "s/\(gtk-theme-name=\).*/\1\"$theme_name\"/" ~/.gtkrc-2.0
			sed -i "s/\(gtk-theme-name=\).*/\1$theme_name/" ~/.config/gtk-3.0/settings.ini
			break
			;;
	esac
	done

	exit 0
}

function font()
{
	local location=~/.xrdb/st
	printf "Pesquise pelo nome da fonte: "
	read font_name

	printf "==> Fontes encontradas\n"
	PS3='Selecione uma das fontes encontradas: '
	select selected_font in $(fc-list | awk -F'[:,]' "/$font_name/ { gsub(/ /,\"\",\$2); print \$2 }" | sort | uniq); do
	case "$selected_font" in
		*)
			printf "==> Fonte selecionada: $selected_font\n"
			printf "==> Determinando tamanho da fonte..."
			sizes=$(fc-list : family pixelsize | awk -v ORS=" " -F= "/$selected_font:pixelsize/ { print \$2 }")
			if [ -z "$sizes" ]; then
				printf "não encontrado.\nDigite um tamanho: "
				read size
			else
				printf "fonte em bitmap.\n"
				PS3='Selecione um tamanho permitido: '
				select size in $sizes; do
					break
				done
			fi
			sed -i "s/^\\(st.font:\\s*\\).*/\\1${selected_font}:pixelsize=${size}:antialias=true:autohint=true/" $location
			xrdb -merge $location
			killall -USR1 $TERMINAL
			break
			;;
	esac
	done

	exit 0
}

function me()
{
	${EDITOR} "$name"
}

function polybar()
{
	${EDITOR} ~/.config/polybar/config
	killall -USR1 polybar
}

if ! (( $# )); then
	usage
	exit
fi

if [ -z $config_files[$1] ]; then
	echo $1
fi

case "$1" in
	-h|--help) usage; exit ;;
	*) command="$1"; shift; break ;;
esac

type $command &>/dev/null && $command $* || die "option not found"

printf "${blue}Configuração atualizada com sucesso.${reset}\n"

# vim: ft=sh
